package com.my.easyrules.test;

import com.my.easyrules.domain.Person;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rule;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngine;
import org.jeasy.rules.core.DefaultRulesEngine;
import org.jeasy.rules.mvel.MVELRule;
import org.jeasy.rules.mvel.MVELRuleFactory;
import org.jeasy.rules.support.reader.YamlRuleDefinitionReader;

import java.io.FileReader;


public class ShopLauncher {

    /*
    我们定义两个规则：

    规则1：可以更新Person实例，判断年龄是否大于18岁，并设置成人标志。
    规则2：判断此人是否为成年人，并拒绝儿童（即非成年人）购买酒精。

    显然，规则1的优先级要大于规则2，我们可以设置规则1的Priority为1，
    规则2的Priority为2，这样保证规则引擎在执行规则的时候，按优先级的顺序执行规则。
     */
    public static void main(String[] args) throws Exception {
        //创建一个Person实例(Fact)
        Person tom = new Person("Tom", 14);
        Facts facts = new Facts();
        facts.put("person", tom);

        //创建规则1
        Rule ageRule = new MVELRule()
                .name("age rule")
                .description("Check if person's age is > 18 and marks the person as adult")
                .priority(1)
                .when("person.age > 18")
                .then("person.setAdult(true);");

        //创建规则2
        MVELRuleFactory ruleFactory = new MVELRuleFactory(new YamlRuleDefinitionReader());
//        Resource classPathResource = new ClassPathResource("alcohol-rule.yml");
//        String filename = classPathResource.getFilename();
//        File file = classPathResource.getFile();
//        Rule weatherRule3 = ruleFactory.createRule(new FileReader("/"));
        Rule weatherRule3 = ruleFactory.createRule(
                new FileReader("D:\\IdeaProjects\\timo-tool\\timo\\timo-test\\timo-easy-rules\\src\\main\\resources\\alcohol-rule.yml"));


        Rules rules = new Rules();
        rules.register(ageRule);
        rules.register(weatherRule3);

        //创建规则执行引擎，并执行规则
        RulesEngine rulesEngine = new DefaultRulesEngine();
        System.out.println("Tom: Hi! can I have some Vodka please?");
        rulesEngine.fire(rules, facts);
    }
}